<template>
  <div class="search">
    <el-autocomplete
      v-model="search"
      :fetch-suggestions="findByHospitalName"
      :trigger-on-focus="false"
      class="form"
      clearable
      placeholder="请输入医院名称"
      @select="toHospitalDetail"
    />
    <el-button
      :icon="Search"
      size="default"
      type="primary"
      @click="getHospitalList"
      >搜索</el-button
    >
  </div>
</template>
<script lang="ts" name="Search" setup>
import { Search } from "@element-plus/icons-vue";
import { doFindByHospitalName } from "@/api/home";
import { ref } from "vue";
import { Hospital, Result, SearchSelectItem } from "@/types/types.ts";
import router from "@/router";

let search = ref("");

let emits = defineEmits(["getHospitalList"]);

let searchSelectItemList = Array<SearchSelectItem>();
// 搜索框查询
const findByHospitalName = async (keyword: string, cb: any) => {
  searchSelectItemList = [];
  let result: Result = await doFindByHospitalName(keyword);
  if (result.code === 200) {
    console.log(result.data);
    result.data.forEach((item: Hospital) => {
      searchSelectItemList.push(new SearchSelectItem(item.hosname, item));
    });
  }
  cb(searchSelectItemList);
};

// 详情页
function toHospitalDetail() {
  if (searchSelectItemList) {
    let findItem = null;
    searchSelectItemList.forEach((item) => {
      if (item.value === search.value) {
        findItem = item.link;
      }
    });
    if (findItem) {
      console.log("findItem", findItem);
      router.push({
        path: "/hospital/bookingRegister",
        query: {
          hoscode: findItem.hoscode,
        },
      });
    }
  }
}

// 搜索框选择 => 调用父组件查询方法
function getHospitalList() {
  emits("getHospitalList", search.value);
}
</script>

<style lang="scss" scoped>
.search {
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10px 0;
  ::v-deep(.el-input__wrapper) {
    width: 600px;
    margin-right: 10px;
  }
}
</style>
